package correspondence;

public class Demo1 {
    public static void main(String[] args) {
        Printer1 p = new Printer1();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    synchronized (Printer1.class) {
                        //子类不能抛出比父类还大的异常，故只能try了
                        try {
                            p.print1();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (Printer1.class) {
                        try {
                            p.print2();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();
    }
}
class Printer1{
    int flag = 1;
    public void print1() throws InterruptedException {

        if (flag != 1) {
            //线程1等待
            Printer1.class.wait();

        }
        System.out.print("a");
        System.out.print("b");
        System.out.print("c");
        System.out.println();
        flag = 2;
        //随机唤醒一个线程
        Printer1.class.notify();
    }
    public void print2() throws InterruptedException {
        if (flag != 2) {
            Printer1.class.wait();
        }
        System.out.print("1");
        System.out.print("2");
        System.out.print("3");
        System.out.println();
        flag = 1;
        Printer1.class.notify();
    }
}
